package com.xauto.pioneer.appuser.activity.mine;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.umeng.socialize.UMShareAPI;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.activity.common.WebViewActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.ConfigCallBack;
import com.xauto.pioneer.appuser.interfaces.ShareInfoCallBack;
import com.xauto.pioneer.appuser.model.ClientVersion;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.ShareInfo;
import com.xauto.pioneer.appuser.util.DataCleanManager;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.PackageUtil;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.PromptDialog;
import com.xauto.pioneer.appuser.view.ShareDialog;
import com.xauto.pioneer.appuser.view.TopBar;

import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/***
 * 设置中心页面
 * @author Lemon Sun 12 Feb 19:27
 */
public class SettingActivity extends BaseActivity {

    @Bind(R.id.topBar) TopBar topBar;
    /** 显示当前版本*/
    @Bind(R.id.tvSetCheckVersion) TextView tvSetCheckVersion;
    /** 清理缓存*/
    @Bind(R.id.tvSetCleanCache) TextView tvSetCleanCache;
    /** 弹出退出登录提示框*/
    private PromptDialog promptLogoutDialog;
    /** 弹出清除缓存提示框*/
    private PromptDialog promptCleanCacheDialog;
    /** 清理缓存大小*/
    private long cacheSize;
    private ShareDialog shareDialog;

    @Override
    protected int getContentView() {
        return R.layout.ac_mine_setting;
    }

    @Override
    protected void initView() {
        topBar.showView(TopBar.TITLE, TopBar.LEFT_IMAGE_BTN);
        topBar.setText(TopBar.TITLE, getString(R.string.top_bar_setting));
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        promptCleanCacheDialog = new PromptDialog(mContext, getString(R.string.notice), getString(R.string.clear_cache_tip),
                getString(R.string.confirm), getString(R.string.cancel), getString(R.string.dialogpic_cache),new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataCleanManager.deleteFilesByDirectory(mContext.getFilesDir());
                //清除缓存
                promptCleanCacheDialog.dismiss();
                DataCleanManager.cleanExternalCache(mContext);
                DataCleanManager.cleanInternalCache(mContext);
                try {
                    updateCache(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                promptCleanCacheDialog.dismiss();
            }
        });

        promptLogoutDialog = new PromptDialog(mContext, getString(R.string.notice), getString(R.string.text_logout),
                getString(R.string.logout), getString(R.string.cancel), getString(R.string.dialogpic_common),new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出
                promptLogoutDialog.dismiss();
                load();
                //todo 暂时直接登出成功
//                PreferencesUtils.clear(mContext);
//                setResult(Constants.RESULT_CLOSE_PAGE);
//                finish();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                promptLogoutDialog.dismiss();
            }
        });
    }

    @Override
    protected void initData() {
        try {
            updateCache(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvSetCheckVersion.setText("V" + PackageUtil.getAppVersionName(mContext));

        lHandler = new BaseLHttpHandler(mContext, true, true) {

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                PreferencesUtils.clear(mContext);
                setResult(Constants.RESULT_CLOSE_PAGE);
                finish();
            }
        };
    }

    @OnClick({R.id.llSetAboutMe, R.id.llSetCheckVersion, R.id.llSetCleanCache,
            R.id.llSetShareApp, R.id.llSetFeedback, R.id.llSetLogout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llSetAboutMe:
                //关于我们
                WebViewActivity.startAction(mContext,5);
                break;
            case R.id.llSetCheckVersion:
                //检查新版本
                updateVersion();
                break;
            case R.id.llSetCleanCache:
                //清理缓存
                try {
                    cacheSize = getCurrentCache();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(cacheSize == 0) {
                    ToastUtil.showShort(mContext, "暂无可清理的缓存");
                    return;
                }
                promptCleanCacheDialog.show();
                break;
            case R.id.llSetShareApp:
                //分享软件
                DataLoadUtil.getShareInfo(mContext, "1", new ShareInfoCallBack() {
                    @Override
                    public void getShareInfo(final ShareInfo shareInfo) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (shareDialog == null){
                                    shareDialog = new ShareDialog(mContext, SettingActivity.this, shareInfo);
                                }
                                if (!shareDialog.isShowing())shareDialog.show();
                            }
                        });
                    }
                });
//                share_info = new ShareInfo();
//                share_info.setContent("分享内容");
//                share_info.setShare_url("http://www.baidu.com");
//                share_info.setTitle("分享标题");
//                share_info.setShare_image(new Image("http://img.zcool.cn/community/01057e56f1ef1632f875a944d7985a.jpg@900w_1l_2o_100sh.jpg","http://pic8.qiyipic.com/image/20140602/4b/43/c4/v_106470326_m_601_320_180.jpg"));

                break;
            case R.id.llSetFeedback:
                //意见反馈
                startActivity(new Intent(mContext, SettingFeedbackActivity.class));
                break;
            case R.id.llSetLogout:
                //退出登录
                promptLogoutDialog.show();
                break;
        }
    }

    void load() {
        new LHttpLib().logout(mContext, memberId, JPushInterface.getRegistrationID(mContext), lHandler);
    }

    /** 获取当前缓存大小*/
    private long getCurrentCache() throws Exception {
//        long cacheSize = DataCleanManager.getFolderSize(mContext.getCacheDir());
        long cacheSize = 0;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += DataCleanManager.getFolderSize(mContext.getExternalCacheDir());
        }
        return cacheSize;
    }

    /***
     * 刷新当前缓存
     * @param isPromptSuccess 是否是清除之后，需要弹出清楚成功提示
     * @throws Exception
     */
    private void updateCache(boolean isPromptSuccess) throws Exception {
//        long cacheSize = DataCleanManager.getFolderSize(mContext.getCacheDir());
        long cacheSize = 0;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += DataCleanManager.getFolderSize(mContext.getExternalCacheDir());
        }
        Log.e(TAG, "cache = " + DataCleanManager.getFormatSize(cacheSize));
        if(isPromptSuccess) {
            new PromptDialog(mContext, "已清理" + DataCleanManager.getFormatSize(this.cacheSize) + "缓存").show();
        }else {
        }
        tvSetCleanCache.setText(DataCleanManager.getFormatSize(cacheSize));
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case  1:
                    ToastUtil.showShort(mContext,"分享成功");
                    break;
                case  2:
                    ToastUtil.showShort(mContext,"分享失败");
                    break;

            }
        }
    };

    //对于的低端手机可能会有如下问题，从开发者app调到qq或者微信的授权界面，后台把开发者app杀死了，这样，授权成功没有回调了，可以用如下方式避免：（一般不需要添加，如有特殊需要，可以添加）
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    /************************************************ 版本更新 starting **************************************************/
    private void updateVersion(){
        DataLoadUtil.getConfig(mContext, new ConfigCallBack() {
            @Override
            public void getConfig() {
                FinalDb finalDb = FinalDb.create(mContext);
                List<ClientVersion> client = finalDb.findAll(ClientVersion.class);
                if (client != null && client.size() >0){
                    doUpdate(client.get(0));
                }
            }
        });
    }
    private PromptDialog updatePromptDialog;

    private void doUpdate(ClientVersion clientVersion) {
        if("1".equals(clientVersion.need_update)) {
            getUpdatePromptDialog(clientVersion).show();
        } else {
            if("1".equals(clientVersion.has_update) && "1".equals(clientVersion.is_tips)) {
                getUpdatePromptDialog(clientVersion).show();
            } else {
//                switchPage();
            }
        }
    }

    private PromptDialog getUpdatePromptDialog(final ClientVersion clientVersion) {
        if("1".equals(clientVersion.need_update)) {
            //强制更新，一个按钮&隐藏取消按钮
            updatePromptDialog = new PromptDialog(mContext, getString(R.string.notice), clientVersion.tips_content,
                    getString(R.string.update_now), getString(R.string.dialogpic_common),new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updatePromptDialog.dismiss();
                    download(clientVersion.download_type, clientVersion.download_url);
                }
            });
        } else {
            updatePromptDialog = new PromptDialog(mContext, getString(R.string.notice), clientVersion.tips_content, getString(R.string.update_now),
                    getString(R.string.update_later), getString(R.string.dialogpic_common),new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updatePromptDialog.dismiss();
                    download(clientVersion.download_type, clientVersion.download_url);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updatePromptDialog.dismiss();
                }
            }, false);
        }
        return updatePromptDialog;
    }

    private void download(String type, String download_url) {
        if(type.equals(Constants.DOWNLOAD_TYPE_WEB)) {
            downloadWeb(download_url);
        }
        if(type.equals(Constants.DOWNLOAD_TYPE_APK)) {
            downloadApk(download_url);
        }
    }

    private void downloadWeb(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    private void downloadApk(String url) {
        final ProgressDialog downloadDialog = new ProgressDialog(mContext, R.style.LightDialog);
        downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        downloadDialog.setTitle("下载中");
        downloadDialog.setIndeterminate(false);
        downloadDialog.setCancelable(false);
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.show();
        new FinalHttp().download(url, Constants.APK_TARGET, new AjaxCallBack<File>() {
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Log.e(TAG, "errorNo:" + errorNo + ",strMsg:" + strMsg);
                prompt("出错：" + strMsg);
            }

            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                int progress;
                if (current != count && current != 0) {
                    progress = (int) (current / (float) count * 100);
                } else {
                    progress = 100;
                }
                downloadDialog.setProgress(progress);
                Log.e(TAG, "download:" + progress + "%");
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.e(TAG, "start download");
            }

            @Override
            public void onSuccess(File t) {
                super.onSuccess(t);
                Log.e(TAG, "download success");
                downloadDialog.dismiss();
                PackageUtil.installNormal(mContext, Constants.APK_TARGET);
            }
        });
    }
    /************************************************ 版本更新 ending **************************************************/
}
